/*
 * @Author       : mark
 * @Date         : 2020-06-17
 * @copyleft Apache 2.0
 */ 
#ifndef HEAP_TIMER_H
#define HEAP_TIMER_H

#include <queue>
#include <unordered_map>
#include <time.h>
#include <algorithm>
#include <arpa/inet.h> 
#include <functional> 
#include <assert.h> 
#include <chrono>
#include "../log/log.h"

using TimeoutCallBack = std::function<void()>;      //回调函数
using Clock = std::chrono::high_resolution_clock;   //
using MS = std::chrono::milliseconds;               //
using TimeStamp = Clock::time_point;                //

struct TimerNode {
    int sock_fd;
    TimeStamp expires;
    TimeoutCallBack callback;
    bool operator<(const TimerNode& t) const {
        return expires < t.expires;
    }
};
class HeapTimer {
public:
    HeapTimer() {
        container_.resize(1); 
    }

    ~HeapTimer() { clear(); }
    
    bool empty();
    size_t size();
    TimerNode top();
    void pop();
    void clear();
    
    void update(int sock_fd, int new_expires);          //更新fd的超时时间

    void push(int sock_fd, int time_out, const TimeoutCallBack& callback);

    void delFd(int sock_fd);               //删除指定fd的结点

    int GetNextTick();                      //获取下一次的超时时间

private:
    void tick();                            //删除超时结点并调用work执行callback
    void del(size_t i);                     //删除指定结点
    void up(size_t i);                      //上浮结点
    void down(size_t index, size_t n);      //下沉结点
    void swap(size_t i, size_t j);          //交换结点

    std::vector<TimerNode> container_;      //底层容器
    std::unordered_map<int, size_t> ref_;   //socket fd到下标的映射
};

#endif //HEAP_TIMER_H